define(['zepto', "../base/openapi"], function($, OpenAPI) {
	var Util = {
		loadList: function(me, listName, url, params, isLoadFromServer) {
			var list = me.component(listName); // 获取组件
			list.config.url = url;
			params.client_id = OpenAPI.client_id;
			if (isLoadFromServer) {
				list.setRequestParams(params);
			} else {
				// list.setRequestParams(params, false);
				if (list.isExistStoreData(listName)) {
					list.loadListByStoreData(url, params);
				} else {
					list.setRequestParams(params);
				}
			}
		},
		loadTweetDetailList: function(me, listName, url, params, isLoadFrom, isLoadFromID) {
			var list = me.component(listName); // 获取组件
			list.config.url = url;
			params.client_id = OpenAPI.client_id;
			var oldList = Piece.Store.loadObject("cube-list-" + isLoadFrom)
			//当List是根据不同的用户而变化时，通过isLoadFrom拿取缓存中的标识ID与idLoadFromID比较判断是否拿缓存，common/common-seeUser
			if (oldList === null) {
				list.setRequestParams(params);
			} else {
				if (oldList[0].id === isLoadFromID) {
					list.loadListByStoreData(url, params);
				} else {
					list.setRequestParams(params);
				}
			}

		},
		loadDifferentUsersList: function(me, listName, url, params, isLoadFrom, isLoadFromID, reload) {
			var list = me.component(listName); // 获取组件
			list.config.url = url;
			params.client_id = OpenAPI.client_id;
			var oldList = Piece.Store.loadObject("cube-list-" + isLoadFrom)
			if (reload) {
				list.setRequestParams(params);
				return;
			}
			//当List是根据不同的用户而变化时，通过isLoadFrom拿取缓存中的标识ID与idLoadFromID比较判断是否拿缓存，common/common-seeUser
			if (oldList === null) {
				list.setRequestParams(params);
			} else {
				if (oldList[0].author === isLoadFromID) {
					list.loadListByStoreData(url, params);
				} else {
					list.setRequestParams(params);
				}
			}

		},
		loadDifferentCommentList: function(me, listName, url, params, isLoadFrom, isLoadFromID) {
			var list = me.component(listName); // 获取组件
			list.config.url = url;
			params.client_id = OpenAPI.client_id;
			var recordID = Piece.Store.loadObject("recordID");
			if (recordID == isLoadFromID) {
				list.loadListByStoreData(url, params);
			} else {
				list.setRequestParams(params);
				Piece.Store.saveObject("recordID", isLoadFromID);
			}

		},

		reloadPage: function(url) {
			setTimeout(function() {
				Backbone.history.navigate("#", {
					trigger: false
				});

				Backbone.history.navigate(url, {
					trigger: true
				});

			}, 1000);
		},
		cleanStoreListData: function(id) {
			// 在注销登陆时，调用此方法清除我的空间缓存
			var CACHE_ID = 'cube-list-' + id;
			window.localStorage.removeItem(CACHE_ID);
			window.localStorage.removeItem(CACHE_ID + "-config");
			window.localStorage.removeItem(CACHE_ID + "-params");
			window.localStorage.removeItem(CACHE_ID + "-scrollY");
		},
		cleanDetailSession: function() {
			//拿出detail的session缓存，清除后再重新请求
			var id = Util.request("id");
			var landId = "L" + id;
			window.sessionStorage.removeItem(id);
			window.sessionStorage.removeItem(landId);
		},
		liveATagEvent: function(e) {
			var me = this;
			var fullUrl = $(this).attr("href");
			var url;
			//["http://www.oschina.net/news/{Long news id}",
			// "http://www.oschina.net/p/{String unique ident}",
			//  "http://my.oschina.net/{String unique ident}", 
			//  "http://my.oschina.net/u/{Long user id}",
			//   "http://my.oschina.net/u/{Long user id}/blog/{Long blog id}", 
			//   "http://my.oschina.net/{String unique ident}/blog/{Long blog id}", 
			//   "http://www.oschina.net/question/{Long user id}_{Long question id}", 
			//   "http://my.oschina.net/u/{Long user id}/tweet/{Long tweet id}", 
			//   "http://my.oschina.net/{String unique ident}/tweet/{Long tweet id}"]
			e.preventDefault();
			//如果是#号不做处理
			if (fullUrl === undefined || fullUrl === "#") {
				return;
			}
			url = fullUrl.split("/");

			if (url[2] === "my.oschina.net" || url[2] === "www.oschina.net") {
				var path = "";
				var id;

				if (url[2] === "www.oschina.net" && url[3] === "news") {
					console.info(url + "===是新闻");
					id = url[4];
					Util.gotoNewsDetail(id);
				}
				if (url[2] === "www.oschina.net" && url[3] === "p") {
					console.info(url + "===是软件");
					id = fullUrl;
					Util.goToProjectDetail(id);
				}
				if (url[2] === "www.oschina.net" && url[3] === "question") {
					console.info(url + "===是问答详情");
					refId = url[4];
					// http://www.oschina.net/question/12_133891
					var id = refId.substr(-6, 6);
					Util.goToQuestionDetail(id);
				}
				if (url[2] === "my.oschina.net" && url[3] !== "u" && url[3] !== "p" && url[3] !== "news" && url[3] !== "question" && url[5] === undefined) {
					console.info(url + "===是个人空间");
					id = url[3];
					Util.goToUserInfo(id);
				}
				if (url[2] === "my.oschina.net" && url[3] === "u" && url[5] === undefined) {
					console.info(url + "===是个人空间");
					id = url[4];
					Util.goToUserInfo(id);
				}
				if (url[2] === "my.oschina.net" && url[3] === "u" && url[5] === "blog") {
					console.info(url + "===是个人博客");
					id = url[6];
					Util.gotoBlogDetail(id);
				}
				if (url[2] === "my.oschina.net" && url[3] !== "u" && url[4] === "blog") {
					console.info(url + "===是个人博客");
					id = url[5];
					Util.gotoBlogDetail(id);
				}
				if (url[2] === "my.oschina.net" && url[4] === "blog") {
					console.info(url + "===是个人博客");
					id = url[5];
					Util.gotoBlogDetail(id);
				}
				if (url[2] === "www.oschina.net" && url[3] === "question" && url[5] === undefined) {
					console.info(url + "===是问答");
					id = url[4];
				}
				if (url[2] === "my.oschina.net" && url[3] === "u" && url[5] === "tweet") {
					console.info(url + "===是动弹");
					id = url[6];
				}
				if (url[2] === "my.oschina.net" && url[3] == "wfire" && url[4] == "tweet") {
					console.info(url + "===是动弹");
					id = url[5];
					Util.gotoTweet(id);
				}
				if (url[2] === "my.oschina.net" && url[3] === "fomy" && url[4] === "blog") {
					console.info(url + "===是个人博客");
					id = url[5];
					Util.gotoBlogDetail(id);
				}
				if (url[2] === "www.oschina.net" && url[3] === "action" && url[4] === "project") {
					console.info(url + "===弹出框");
					var ref = window.open(fullUrl, '_blank', 'location=yes');
				}
				if (url[2] === "www.oschina.net" && url[3] === "translate") {
					console.info(url + "===弹出框");
					var ref = window.open(fullUrl, '_blank', 'location=yes');
				}

				console.info(path);
				console.info(id);
			} else {
				//如果不是oschina的地址，则使用innerview弹出。
				var ref = window.open(fullUrl, '_blank', 'location=yes');
				return false;
			}

		},
		gotoTweet: function(id) {
			Backbone.history.navigate("tweet/tweet-detail?" + "id=" + id, {
				trigger: true
			});
		},
		goToQuestionDetail: function(id) {
			var fromType = 2;
			var com = 2;
			Backbone.history.navigate("question/question-detail?" + "id=" + id + "&com=" + com + "&fromType=" + fromType, {
				trigger: true
			});
		},
		gotoBlogDetail: function(id) {
			var fromType = 3;
			var com = 5;
			Backbone.history.navigate("news/news-blog-detail?" + "id=" + id + "&com=" + com + "&fromType=" + fromType, {
				trigger: true
			});
		},
		gotoNewsDetail: function(id) {
			var fromType = 4;
			var com = 1;
			Backbone.history.navigate("news/news-detail?" + "id=" + id + "&com=" + com + "&fromType=" + fromType, {
				trigger: true
			});
		},
		goToProjectDetail: function(id) {
			Backbone.history.navigate("project/software-detail?" + "url=" + id, {
				trigger: true
			});
		},
		goToUserInfo: function(id) {
			var me = this;
			if (/^\d+$/.test(id)) {
				optionsID = {
					friend: id,
					dataType: 'jsonp'
				}
			} else {
				optionsID = {
					friend_name: id,
					dataType: 'jsonp'
				}
			}
			Util.Ajax(OpenAPI.user_information, "GET", optionsID, 'json', function(data, textStatus, jqXHR) {
				var author = data.name;
				author = encodeURI(author);
				var authorid = data.user;
				Backbone.history.navigate("common/common-seeUser?" + "fromAuthor=" + author + "&fromAuthorId=" + authorid, {
					trigger: true
				});
			}, null);
		},
		StripHtml: function(html) {
			html = html || "";
			var scriptregex = "<scr" + "ipt[^>.]*>[sS]*?</sc" + "ript>";
			var scripts = new RegExp(scriptregex, "gim");
			html = html.replace(scripts, " ");

			//Stripts the <style> tags from the html
			var styleregex = "<style[^>.]*>[sS]*?</style>";
			var styles = new RegExp(styleregex, "gim");
			html = html.replace(styles, " ");

			//Strips the HTML tags from the html
			var objRegExp = new RegExp("<(.| )+?>", "gim");
			var strOutput = html.replace(objRegExp, " ");

			//Replace all < and > with &lt; and &gt;
			strOutput = strOutput.replace(/</, "&lt;");
			strOutput = strOutput.replace(/>/, "&gt;");

			objRegExp = null;
			return strOutput;
		},

		getIdFromUrl: function(moduleName, url) {
			var names = url.split("/");
			var index = names.indexOf(moduleName);
			return names[index + 1];

		},
		imgGoToUserInfor: function(imgEl) {
			var $target = $(imgEl.currentTarget);
			var id = $target.attr("data-id");
			var author = $target.attr("data-author");
			var authorid = $target.attr("data-authorid");
			author = encodeURI(author);
			Backbone.history.navigate("common/common-seeUser?id=" + id + "&fromAuthor=" + author + "&fromAuthorId=" + authorid, {
				trigger: true
			});
		},
		checkLogin: function() {
			var user_info = Piece.Store.loadObject("user_token");
			if (user_info === null || user_info === "" || user_info === undefined) {
				return false;
			}
			var user_timeout = user_info.expires_in;
			var user_systime = user_info.addTime;
			var timeNow = new Date().getTime();
			var calc = timeNow - user_systime;
			var aa = user_timeout - (calc / 1000)
			if ((calc / 1000) < user_timeout) {
				return true;
			} else {
				return false;
				window.localStorage.removeItem("user_token");
				window.localStorage.removeItem("user_message");
			}
		},
		checkConnection: function() {
			var networkState = navigator.connection.type;

			var states = {};
			states[Connection.UNKNOWN] = 'Unknown connection';
			states[Connection.ETHERNET] = 'Ethernet connection';
			states[Connection.WIFI] = 'WiFi connection';
			states[Connection.CELL_2G] = 'Cell 2G connection';
			states[Connection.CELL_3G] = 'Cell 3G connection';
			states[Connection.CELL_4G] = 'Cell 4G connection';
			states[Connection.NONE] = 'No network connection';
			return states[networkState];
		},
		bigImg: function(el) {
			//如果confirm出现，那么return，不查看大图。
			if (typeof $('.cube-dialog-screen').get(0) != 'undefined') {
				return;
			};
			var $target = $(el.currentTarget);
			var imgsrc = $target.attr("img-data");
			if (imgsrc == null) {
				imgsrc = $target.attr("src");
			}
			console.info(imgsrc);
			$('.bigImg').attr("src", imgsrc);
			var img = new Image;
			loader = new Piece.Loader({
				autoshow: true, //是否初始化时就弹出加载控件
				target: 'body' //页面目标组件表识
			});
			img.onload = function() {
				var OriginalWidth = img.width;
				OriginalHeight = img.height;
				bigImg.show({
					ImgWidth: OriginalWidth,
					ImgHeight: OriginalHeight
				});
				loader.hide();

			};
			img.src = imgsrc;
		},
		removeImg: function(htmlstr) {
			var replaceHtml;
			var loadImg = Piece.Session.loadObject("loadImg");
			// alert(loadImg);
			// alert(htmlstr);

			//勾选了加载图片
			if (loadImg == "1") {
				replaceHtml = htmlstr;
				return replaceHtml;
			}

			//没勾选加载图片，那么在wifi的网络下加载图片
			if (navigator.connection) {
				var networkState = navigator.connection.type;

				var states = {};
				states[Connection.UNKNOWN] = 'Unknown connection';
				states[Connection.ETHERNET] = 'Ethernet connection';
				states[Connection.WIFI] = 'WiFi connection';
				states[Connection.CELL_2G] = 'Cell 2G connection';
				states[Connection.CELL_3G] = 'Cell 3G connection';
				states[Connection.CELL_4G] = 'Cell 4G connection';
				states[Connection.NONE] = 'No network connection';
				if (states[networkState] == "WiFi connection") {
					replaceHtml = htmlstr;
					return replaceHtml;
				}

			}
			//其他网络条件下不加载图片
			replaceHtml = htmlstr.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, " ");

			return replaceHtml;

		},

		request: function(paras) {
			var url = location.href;
			var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");

			var returnValue;
			for (i = 0; i < paraString.length; i++) {
				var tempParas = paraString[i].split('=')[0];
				var parasValue = paraString[i].split('=')[1];

				if (tempParas === paras)
					returnValue = parasValue;
			}

			if (typeof(returnValue) == "undefined") {
				return "";
			} else {
				return returnValue;
			}
		},
		roundRobin: function() {
			var me = this;
			var token = Piece.Store.loadObject("user_token");
			if (token === null) {
				window.clearInterval(intRound);
			} else {
				var checkLogin = me.checkLogin();
				var user_access_token = token.access_token;
				if (checkLogin) {
					window.clearInterval(intRound);
					window.intRound = setInterval(function() {
						$.ajax({
							timeout: 2000 * 1000,
							url: OpenAPI.user_notice,
							type: "GET",
							dataType: "jsonp",
							data: {
								access_token: user_access_token,
								client_id: OpenAPI.client_id,
								dataType: "jsonp"
							},
							beforeSend: function(xhr, settings) {},
							success: function(data, textStatus, jqXHR) {
								Piece.Session.saveObject('Prompt', data)
								var userPromptNum = data.replyCount + data.msgCount + data.referCount;
								if (userPromptNum != 0) {
									//menu
									$('.userPrompt').css("display", "block");
									$('.userPromptNum').html(userPromptNum);
									//nav
									if (data.msgCount != 0) {
										$(me.el).find('.commentPrompt').css("display", "inline-block");
										$(me.el).find('.commentPrompt').html(data.msgCount);
									}
									if (data.replyCount != 0) {
										$(me.el).find('.criticPrompt').css("display", "inline-block");
										$(me.el).find('.criticPrompt').html(data.replyCount);
									}
									if (data.referCount != 0) {
										$(me.el).find('.atmePrompt').css("display", "inline-block");
										$(me.el).find('.atmePrompt').html(data.referCount);
									}
								}

							},
							error: function(e, xhr, type) {},
							complete: function(xhr, status) {

							}
						})
						//----------------------foot menu----- ---------------------

					}, 1000000)

				} else {
					window.localStorage.removeItem("user_token");
					window.localStorage.removeItem("user_message");
				}
			}

		},
		eventBubble: function(el) {
			//A标签事件 与 列表详情 事件，事件冒泡.
			var eventHTML = el.target.outerHTML;
			var eventB = eventHTML.substr(1, 4);
			var eventLink = eventHTML.substr(12, 11); //删除动弹截取。事件冲突
			//去掉空格
			eventB = eventB.replace(/^\s*/, "").replace(/\s*$/, "");
			eventLink = eventLink.replace(/^\s*/, "").replace(/\s*$/, "");
			if (eventB == 'div' || eventLink == "cube-dialog") {
				return true
			} else {
				return false
			}
		},
		Ajax: function(urls, types, datas, dataTypes, successCallback, errorCallback, completeCallback) {
			datas.client_id = OpenAPI.client_id;
			var loader;
			var meUrls = urls;
			$.ajax({
				timeout: 2000 * 1000,
				url: urls,
				type: types,
				data: datas,
				dataType: "jsonp",
				beforeSend: function(xhr, settings) {
					loader = new Piece.Loader({
						autoshow: true, //是否初始化时就弹出加载控件
						target: 'body' //页面目标组件表识
					});
				},
				success: function(data, textStatus, jqXHR) {
					// console.info(data);
					// if (data.error === "401") {
					// 	window.localStorage["user_token"] = null;
					// 	window.localStorage["user_info"] = null;
					// 	new Piece.Toast("登录超时，请重新");
					// } else if (data.error === "400") {
					// 	new Piece.Toast('请输入正确的邮箱和密码');
					// }
					if (successCallback !== null && successCallback !== undefined) {
						successCallback(data, textStatus, jqXHR);
					}

				},
				error: function(e, xhr, type) {
					if (errorCallback !== null && errorCallback !== undefined) {
						errorCallback(e, xhr, type);
					} else {
						console.info("============")
						console.info(xhr);
						console.info(type);
						console.info(e);

						new Piece.Toast("请求出错，请稍后尝试");
					}
				},
				complete: function(xhr, status) {
					console.info(status)
					console.info(xhr)

					loader.hide();
					if (completeCallback && completeCallback()) {
						completeCallback(xhr, status);
					}
				}
			});
		},
		AjaxNoLoading: function(urls, types, datas, dataTypes, successCallback, errorCallback, completeCallback) {
			datas.client_id = OpenAPI.client_id;
			var loader;
			var meUrls = urls;
			$.ajax({
				timeout: 2000 * 1000,
				url: urls,
				type: types,
				data: datas,
				dataType: "jsonp",
				beforeSend: function(xhr, settings) {
				},
				success: function(data, textStatus, jqXHR) {
					if (successCallback !== null && successCallback !== undefined) {
						successCallback(data, textStatus, jqXHR);
					}

				},
				error: function(e, xhr, type) {
					if (errorCallback !== null && errorCallback !== undefined) {
						errorCallback(e, xhr, type);
					} else {
						new Piece.Toast("请求出错，请稍后尝试");
					}
				},
				complete: function(xhr, status) {
					if (completeCallback && completeCallback()) {
						completeCallback(xhr, status);
					}
				}
			});
		}

	};
	return Util;
});